package com.fancy.learncenter.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonFinishResultBean;
import com.fancy.learncenter.bean.CartoonFinishWorkBean;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.view.CartoonFinishWorkTurnipNumView;
import com.fancy.learncenter.ui.view.CartoonShowOffPopu;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.TimeUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 完成学习
 */
public class CartoonFinishedActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.my_Listen)
    ImageView myListen;
    @Bind(R.id.turnip_num)
    TextView turnipNumText;
    //    @Bind(R.id.turnip_linear)
//    LinearLayout turnipLinear;
//    @Bind(R.id.mark_num)
//    TextView markNum;
//    @Bind(R.id.mark_linear)
//    LinearLayout markLinear;

    String turnipNumStr;
    String answerStr;
    @Bind(R.id.btn_display)
    Button btnDisplay;
    @Bind(R.id.btn_move_to_first)
    Button btnMoveToFirst;
    JumpIntentKey.QUESTION_ENTER_TYPE type;
    @Bind(R.id.answer_num)
    TextView answerNum;
    @Bind(R.id.turnip_num_view)
    CartoonFinishWorkTurnipNumView turnipNumView;
    @Bind(R.id.answer_total_num)
    TextView answerTotalNum;
    private int turnipNum;
    private CartoonFinishWorkBean finishWorkBean;
    private long durationTime; // 答题时长
    private CartoonShowOffPopu showOffPopu;
    private String questionTotalNum;
    private String rightAnswerNum;
    private String formateData;
    private String homePackageId;
    private String studentHomeworkId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCartoonContentView(R.layout.activity_cartoon_finished, Status.STATUS);
        ButterKnife.bind(this);
        rightAnswerNum = String.valueOf(JumpIntentKey.RIGHT_NUM);
        getIntentData();
        switch (type) {
            case FINISH_WORK:
                finishWork();
                break;
            case DO_IT_AGAIN:
                AnswerView();
                break;
            case CONTINUE_WORK:
                finishWork();
                break;
            case DO_WORK:
                finishWork();
                break;
        }
    }

    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();

        type = (JumpIntentKey.QUESTION_ENTER_TYPE) bundle.getSerializable(JumpIntentKey.QUESTION_ENTER);

        questionTotalNum = bundle.getString(JumpIntentKey.QUESTION_NUM);

        homePackageId = bundle.getString(JumpIntentKey.HOMEWORK_PACKAGE_ID);

        studentHomeworkId = bundle.getString(JumpIntentKey.STUDENTHOMEWORKID);


//        durationTime = bundle.getLong(JumpIntentKey.ANSWER_QUESTION_DURATION);
        durationTime = getRecordTime();
        Log.i("duration-----", durationTime + "");
        formateData = TimeUtil.timeAllFormate(durationTime);

        switch (type) {
            case DO_IT_AGAIN:
                btnDisplay.setVisibility(View.GONE);
                turnipNumView.setVisibility(View.GONE);
                turnipNumText.setVisibility(View.GONE);
                break;
            case FINISH_WORK:
                btnDisplay.setVisibility(View.VISIBLE);

                break;
        }

        btnMoveToFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JumpIntentKey.RIGHT_NUM = 0;
                finish();
            }
        });
        btnDisplay.setOnClickListener(this);
    }


    /**
     * 获取提包答题时长
     */
    private long getRecordTime() {

        long startTime = LoginUserSharePrefernce.getRecordStartTime(String.valueOf(homePackageId));
//        long startTime = 0;
//
//        if (!TextUtils.isEmpty(startTimeStr)) {
//            startTime = Long.valueOf(startTimeStr);
//        }
        Log.i("startTime----", startTime + "");
        long endTime = System.currentTimeMillis();
        Log.i("endTime----", endTime + "");
        long timeDuration = endTime - startTime;
        Log.i("timeDuration----", timeDuration + "");
        long beforeTimeDuration = LoginUserSharePrefernce.getCartoonQuestionTime(homePackageId);

//        long beforeTimeDuration = 0;
//        if (!TextUtils.isEmpty(beforeTimeDurationStr)) {
//            beforeTimeDuration = Long.valueOf(beforeTimeDurationStr);
//        }
        long duration = timeDuration + beforeTimeDuration;
        Log.i("duration----", duration + "");
        LoginUserSharePrefernce.setCartoonQuestionTime(0, homePackageId);
        LoginUserSharePrefernce.setRecordStartTime(0, homePackageId);
        Log.i("duration----", duration + "");
        return duration;
    }

    private void initView() {

        back.setVisibility(View.GONE);

        turnipNum = Double.valueOf(finishWorkBean.getRadishCount()).intValue();
        turnipNumView.setTurnipNum(turnipNum);
        turnipNumStr = "萝卜" + "+" + String.valueOf(turnipNum);
        int index = turnipNumStr.indexOf("+");
        SpannableStringBuilder builder = new SpannableStringBuilder(turnipNumStr);
        TextAppearanceSpan span = new TextAppearanceSpan(this, R.style.text_size22_span);
        builder.setSpan(span, index, turnipNumStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        turnipNumText.setText(builder);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                turnipNumText.measure(0, 0);
                turnipNumText.setWidth(turnipNumText.getMeasuredWidth());

            }
        }, 50);
        AnswerView();

    }

    private void AnswerView() {
        answerStr = "答对 " + rightAnswerNum + "/" + questionTotalNum + "题";
//        SpannableStringBuilder builderAnswer = new SpannableStringBuilder(answerStr);
//        TextAppearanceSpan spanAnswer = new TextAppearanceSpan(this, R.style.text_size30_span);
//        builderAnswer.setSpan(spanAnswer, 2, 2 + rightAnswerNum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//

        answerNum.setText(rightAnswerNum);

        answerTotalNum.setText("/"+questionTotalNum + "题");


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                answerNum.measure(0, 0);
                answerNum.setWidth(answerNum.getMeasuredWidth());
            }
        }, 50);
    }


    /**
     * 完成作业调用接口
     */
    private void finishWork() {

        Map<String, Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        map.put("homeworkPackageId", homePackageId);
        map.put("studentHomeworkId", studentHomeworkId);


        HttpMehtod.getInstance().cartoonCompleteHomeWorks(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonFinishResultBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonFinishResultBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonFinishResultBean>() {
                    @Override
                    public void success(CartoonFinishResultBean dataBean) {
                        if (dataBean != null) {
                            finishWorkBean = dataBean.getResult();
                            rightAnswerNum = finishWorkBean.getRightQuestionCount();
                            questionTotalNum = finishWorkBean.getTotalQuestionCount();
                            initView();
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        JumpIntentKey.RIGHT_NUM = 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:

                break;
            case R.id.btn_display:
                showOffPopu();
                break;

        }
    }

    private void showOffPopu() {

        if (showOffPopu == null) {
            showOffPopu = new CartoonShowOffPopu(this, finishWorkBean, formateData);
        }
        if (!showOffPopu.isShowing()) {
            showOffPopu.showAtLocation(turnipNumView, Gravity.CENTER, 0, 0);
        }

    }

}
